
import { User, IAdminStore } from '@shared/types';
import { SourceData } from '@ugeez/frontend-commons/lib/types';
import { action, observable } from 'mobx';
import { keepAlive } from '@shared/services/account';

const defaultUser: User = {
    id: undefined,
    name: undefined,
    head: undefined,
    auth: undefined,
    roles: undefined,
    isLogined: false,
};

class Store implements IAdminStore {
    
    @observable
    user: User = {...defaultUser};

    locale: string = 'zh_CN';

    constructor() {
        this.locale = localStorage.getItem('locale') || 'zh_CN';
        const token = localStorage.getItem('token');
        if (token) {
            this.login(token);
        }
    }

    @action
    login(auth: string | User) {
        let token: string | undefined = undefined;
        let account: User = this.user;
        if (typeof auth === 'string') {
            token = auth as string;
        } else {
            account = auth as User;
            token = auth.auth;
        }
        if (token) {
            localStorage.setItem('token', token);
        } else {
            console.error(`login with undefined token is incorrect`);
        }
        this.user = {
            ...account,
            auth: token,
            isLogined: !!token,
        };
    }

    logout(): void {
        localStorage.removeItem('token');
        this.dispose();
    }
    
    @action
    async keepAlive(): Promise<void> {
        const user = await keepAlive();
        this.user = {
            ...this.user,
            ...user,
        };
    }

    @action
    updateUser(user: User) {
        const newUser = {
            ...this.user,
            ...user,
        };
        this.user = newUser;
    }

    switchLocale(locale: string) {
        localStorage.setItem('locale', locale);
        window.location.reload();
    }

    dispose(): void {
        this.user = {...defaultUser};
    }
}

const store = window['__STORE__'] || new Store();
window['__STORE__'] = store;

export default store;
